const router = require("koa-router")();
const DB = require("../../module/db");
const sd = require("silly-datetime");

router.get("/", async (ctx) => {
    ctx.body = "后台首页";

}).post("/addComment", async (ctx) => {
    let data1 = ctx.request.body
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm')
    data1.createTime = time
    data1.updateTime = ''
    let data2 = await DB.insert('comment', data1);
    try {
        if (data2.result.ok) {
            ctx.body = {
                type: 1,
                info: {
                    "id": data2.ops[0]._id,
                    "time": data1.createTime
                }
            };
            console.log(time + "：添加评论成功");
        } else {
            ctx.body = {
                type: 0,
                // info: data2.ops[0]._id
            };
        }
    } catch (e) {
        console.log(time + "：" + e);
    }

}).get("/getComment", async (ctx) => {
    let mediaId = ctx.query["mediaId"];
    ctx.body = await DB.find('comment', {"mediaId": mediaId});
    // console.log(data);

}).post("/updateComment", async (ctx) => {
    let _id = ctx.request.body["id"]
    let content = ctx.request.body["content"]
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm')
    let data = await DB.update('comment', {"_id": DB.getObjectId(_id)}, {"content": content, "updateTime": time});
    try {
        if (data.result.ok) {
            ctx.body = {
                type: 1,
                info: {
                    "time": time
                }
            };
            console.log(time + "：修改评论成功");
        } else {
            ctx.body = 0;
        }
    } catch (e) {
        console.log(time + "：" + e);
    }

}).post("/deleteComment", async (ctx) => {
    let _id = ctx.request.body["_id"]
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm')
    let data = await DB.remove1('comment', {"_id": DB.getObjectId(_id)});
    try {
        if (data.result.ok) {
            ctx.body = 1;
            console.log(time + "：删除评论成功");
        } else {
            ctx.body = 0;
        }
    } catch (e) {
        console.log(time + "：" + e);
    }

});

module.exports = router.routes();
